//
//  SDHomeViewController.m
//  SuperDoctor
//
//  Created by 李忠 on 7/5/16.
//  Copyright © 2016 SD. All rights reserved.
//

#import "SDHomeViewController.h"
#import "SDWeatherView.h"
#import "SDNetWorkTool.h"
#import "SDWeatherModel.h"
#import "SDCityModel.h"
#import "SDProvinceViewController.h"
#import "NSUserDefaults+SDExtension.h"
#import "SDCycleAdvertView.h"
#import "SDSelectedSectionView.h"
#import "SDWebImageManager.h"
#import "SDSectionViewController.h"
#import "SDCommonwealViewController.h"
#import <CoreLocation/CoreLocation.h>


@interface SDHomeViewController ()<CLLocationManagerDelegate>

//显示天气的view
@property (nonatomic, strong) SDWeatherView *weatherView;
//获取天气数组
@property (nonatomic, strong) NSArray<SDWeatherModel *> *weathers;
//获取滚动视图
@property (nonatomic, strong) SDCycleAdvertView *cycleView;
//滚动视图的数据源
@property (nonatomic, strong) NSArray *cycles;
//名医通视图
@property (nonatomic, strong) UIImageView *famousIV;
@property (nonatomic, strong) UILabel *famousLb;
//名医通视图的选项框
@property (nonatomic, strong) SDSelectedSectionView *selectdSectionView;
//用于定位
@property (nonatomic, strong) CLLocationManager *locationM;
//经纬度
@property (nonatomic, strong) CLGeocoder *geoc;

@end

@implementation SDHomeViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self setupUI];
    [self setupLayout];
    [self checkLocation];
    [self setSubViewBlock];
    
}
//当位置获取或更新失败会调用的方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSString *errorMsg = nil;
    if ([error code] == kCLErrorDenied) {
        errorMsg = @"访问被拒绝";
    }
    if ([error code] == kCLErrorLocationUnknown) {
        errorMsg = @"获取位置信息失败";
    }
    NSString *addrres = [[NSUserDefaults standardUserDefaults] getValueForKEy:kCurrentCity];
    if (addrres.length == 0) {
        [self loadCurDayWeather:@"上海"];
    }else{
        [self loadCurDayWeather:addrres];
    }
    
}

#pragma mark
#pragma mark - 定位
- (void)checkLocation{
    
    [[SDNetWorkTool shareManager] getAFNetworkReachabilityStatusWithUnknown:^{
        
        [self getPictureWith:@"无网络,请检查网络"];
        
    } Reachable:^{
        
        
    }];
    
    
    
    self.locationM.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationM.distanceFilter = 10;
    
    if ([[UIDevice currentDevice].systemVersion floatValue] > 8.0) {
        
        if ([self.locationM respondsToSelector:@selector(requestWhenInUseAuthorization)] ){
            
            [self.locationM requestWhenInUseAuthorization];
            
        }
        
    }
    self.locationM.delegate = self;
   
    [self.locationM startUpdatingLocation];
}



//位置信息
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    // 最后一个值为最新位置
    CLLocation *currentLocation = [locations lastObject];
    // 根据经纬度反向得出位置城市信息
    
    [self.geoc reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        NSString *string = placemarks.lastObject.administrativeArea;
        NSRange range = NSMakeRange(0, string.length -1);
        string = [string substringWithRange:range];
        
        NSString *addrres = [[NSUserDefaults standardUserDefaults] getValueForKEy:kCurrentCity];
        
        if (addrres.length == 0) {
            [self loadCurDayWeather:@"上海"];
        }
        
        if ([addrres isEqualToString:string]) {
            
             [self loadCurDayWeather:string];
            
        }else{
            
            if (string.length == 0 || addrres.length == 0) {
                [self loadCurDayWeather:@"上海"];
            }else{
                NSString *qiehuan = [NSString stringWithFormat:@"%@切换到%@",addrres,string];
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"定位城市与当前城市不同，是否更换地址？" message:qiehuan preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    [self loadCurDayWeather:addrres];
                }];
                UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self loadCurDayWeather:string];
                    [[NSUserDefaults standardUserDefaults] saveString:string withKey:kCurrentCity];
                }];
        
                [alert addAction:action];
                [alert addAction:sureAction];
                
                [self presentViewController:alert animated:YES completion:nil];
            }
        }
        
    }];
    
    [manager stopUpdatingLocation];
}

//加载城市天气
- (void)loadCurDayWeather:(NSString *)city{
    
    __weak typeof(self) weakSelf = self;
  [[SDWeatherModel shareManager] loadWeatherWitchArea:city success:^(NSArray<SDWeatherModel *> *array) {
      weakSelf.weathers = array;
  } error:^(NSError *error) {

      [self getPictureWith:@"链接超时"];
      
  }];
  
}


- (void)setupUI {
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = kThemeColor;
    self.navigationItem.title = @"巴拉巴拉魔法";
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.cycleView.imageArray = self.cycles;
    
}

- (void)setupLayout{
    [self.weaterView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.mas_equalTo(self.mas_topLayoutGuideBottom).mas_offset(0);
        make.leading.trailing.mas_equalTo(0);
        make.height.mas_equalTo(60);
        
    }];
    
    
    [self.cycleView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.weatherView.mas_bottom);
        make.leading.trailing.mas_equalTo(0);
        make.bottom.mas_equalTo(self.view.mas_centerY);
        
    }];
    
    [self.famousIV mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.cycleView.mas_bottom).mas_offset(5);
        make.leading.mas_equalTo(10);
        make.width.mas_equalTo(20);
        make.height.mas_equalTo(50);
    }];
    [self.famousLb mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.mas_equalTo(self.famousIV.mas_centerY);
        make.leading.mas_equalTo(self.famousIV.mas_trailing).mas_offset(10);
        
    }];
    [self.sectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.famousIV.mas_bottom).offset(5);
        make.leading.trailing.bottom.mas_equalTo(0);
    }];
}

- (void)setSubViewBlock{
    
    __weak typeof(self) weakSelf = self;
    self.weatherView.selectCityBlock = ^{
        SDProvinceViewController *vc = [[SDProvinceViewController alloc] init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    
    //MARK: 选择push到相应的名医通
    self.sectionView.pushVCBlock = ^(NSInteger index, NSString *titleName){
        if (index < 5) {
            
            SDSectionViewController *vc = [[SDSectionViewController alloc] init];
            vc.titleName = titleName;
            vc.index = index;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }else{
            SDCommonwealViewController *commonweal = [[SDCommonwealViewController alloc] init];
            [weakSelf.navigationController pushViewController:commonweal animated:YES];
        }
        
    };
    
    
    
}




#pragma mark
#pragma mark - 懒加载
- (SDWeatherView *)weaterView{
    if (_weatherView == nil) {
        _weatherView = [[SDWeatherView alloc] init];
        _weatherView.backgroundColor = [UIColor colorWithRed:170.0/255 green:239.0/255 blue:219.0/255 alpha:1.0];
        [self.view addSubview:_weatherView];
    }
    return _weatherView;
}
- (SDCycleAdvertView *)cycleView{
    if (_cycleView == nil) {
        _cycleView = [[SDCycleAdvertView alloc] init];
        [self.view addSubview:_cycleView];

    }
    return _cycleView;
}
- (UIImageView *)famousIV{
    if (_famousIV == nil) {
        _famousIV = [[UIImageView alloc] init];
        _famousIV.image = [UIImage imageNamed:@"yj"];
        [self.view addSubview:_famousIV];
    }
    return _famousIV;
}
- (UILabel *)famousLb{
    if (_famousLb == nil) {
        _famousLb = [[UILabel alloc] init];
        _famousLb.text = @"名医通";
        _famousLb.font = [UIFont boldSystemFontOfSize:18];
        [self.view addSubview:_famousLb];
    }
    return _famousLb;
}
- (SDSelectedSectionView *)sectionView{
    if (_selectdSectionView == nil) {
        _selectdSectionView = [[SDSelectedSectionView alloc] init];
        _selectdSectionView.backgroundColor = [UIColor colorWithRed:233/255.0 green:233/255.0 blue:233/255.0 alpha:1.0];
        [self.view addSubview:_selectdSectionView];
    }
    return _selectdSectionView;
}

- (CLLocationManager *)locationM{
    if (_locationM == nil) {
        _locationM = [[CLLocationManager alloc] init];
    }
    return _locationM;
}
-(CLGeocoder *)geoc
{
    if (!_geoc) {
        
        _geoc = [[CLGeocoder alloc] init];
        
    }
    return  _geoc;
}

- (NSArray *)cycles{
    if (_cycles == nil) {
        _cycles= @[
    @"http://img.guahao.com/portal_upload/rollingnews/1453447883150.jpg",
    @"http://img.guahao.com/portal_upload/mediafocus/1461826474435.jpg",
    @"http://img.guahao.com/portal_upload/rollingnews/1461574027543.jpg"
                   ];
    }
    return _cycles;
}


#pragma mark
#pragma mark - 重写set方法
- (void)setWeathers:(NSArray<SDWeatherModel *> *)weathers{
    _weathers = weathers;
    self.weatherView.dataList = weathers;
    
}


-(void)getPictureWith:(NSString *)title{
    
    NSBundle *bundle = [NSBundle bundleForClass:[SVProgressHUD class]];
    NSURL *url = [bundle URLForResource:@"SVProgressHUD" withExtension:@"bundle"];
    NSBundle *imageBundle = [NSBundle bundleWithURL:url];
    
    UIImage* errorImage = [UIImage imageWithContentsOfFile:[imageBundle pathForResource:@"error" ofType:@"png"]];
    
    [SVProgressHUD showImage:errorImage status:title];
    
    [SVProgressHUD setMinimumDismissTimeInterval:2];
    
}

@end
